package com.redis.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author 王霄
 * @describe 订单过期未支付监听
 * @date 2021/1/28
 */
@Component
public class OrderExpirationListener extends MessageListenerAdapter {


    private final static Logger logger = LoggerFactory.getLogger(OrderExpirationListener.class);

    /**
     * 订单支付超时时长(3分钟)
     */
    private final static long DELAY = 3 * 60 * 1000;

    @Resource
    RedisTemplate<String, String> redisTemplate;

    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 获取到失效的 key，进行取消订单业务处理
        String expiredKey = message.toString();
        // new String(pattern) ==> __keyevent@*__:expired
        logger.info("订单号：{},3分钟内未支付", expiredKey);
    }

    /**
     * 存入redis
     */
    public void add(String orderId) {
        redisTemplate.opsForValue().set(orderId, orderId, DELAY, TimeUnit.MILLISECONDS);
    }

    /**
     * 从redis中删除
     */
    public void remove(String orderId) {
        redisTemplate.delete(orderId);
    }
}
